package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.PageParam;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper mapper;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetMealService setMealService;

    @Override
    public int update(Category category) {
        return mapper.updateById(category);
    }

    /*删除分类*/
    @Override
    public int delete(long categoryId) {


        //先去查询菜品表，看看菜品表里面有没有什么菜品属于这种分类。
        int count = dishService.findCountByCategoryId(categoryId);
        if (count > 0){
            throw new CustomException("该分类存在菜品数据，禁止删除!");
        }

        //去查询套餐表，看看套餐表里面有没有什么套餐属于这种分类。

        count = setMealService.findCountByCategoryId(categoryId);
        if (count > 0 ){
            throw new CustomException("该分类存在套餐数据，禁止删除！");
        }


        return mapper.deleteById(categoryId);
    }

    /*分页查询*/
    @Override
    public IPage<Category> findPage(PageParam pageParam) {

        //定义查询第几页，每页查询多少条
        IPage<Category> page = new Page<>(pageParam.getPage(), pageParam.getPageSize());

        //执行分页查询
        return mapper.selectPage(page,null);
    }

    /*添加分类*/
    @Override
    public int add(Category category) {
        return mapper.insert(category);
    }
}
